// 基本信息
import { Variable } from "@/api/interface/iot";
import DialogBox from "@/components/DialogBox";
import { TYPE_NAME, TYPE_LIST, UNIT_LIST } from "@/components/JsonSchemaForm/type/type";
import SelectDeviceList from "@/components/Sansan/SelectDeviceListAll";
import { ElForm } from "element-plus";
import { getCurrentInstance, defineComponent, PropType, ComponentInternalInstance } from "vue";
import "./basic-dialog.scss";
import { accessType, control, funcType } from "@/enums/dictEnum";
import { getDevice } from "@/api/modules/iot/device";
import { addDictType, getDictTypeList } from "@/api/modules/system/dict";
import { showMsg, showTips } from "@/utils/util";
import { MessageType } from "@/enums/messageEnum";
import { bizDictType } from "@/utils/cacheUtil";
import { useRoute } from "vue-router";
export default defineComponent({
	props: {
		width: String,
		title: String,
		devicePage: Boolean,
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {}, upload: {} }, param: {} };
			}
		}
	},
	emits: ["submit"],
	setup(props, { attrs, emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		type FormInstance = InstanceType<typeof ElForm>;
		const state = reactive({
			view: "basics",
			isModbus: true // 是否modbus类型
		});
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			key: [{ required: true, message: "请输入变量标识", trigger: "blur" }],
			sn: [{ required: true, message: "请选择设备", trigger: "blur" }]
		});
		const validData = () => {
			formRef.value?.validate(valid => {
				if (valid) {
					props.detail.config!.calc.base = Number(props.detail.config!.calc.base);
					props.detail.config!.calc.mult = Number(props.detail.config!.calc.mult);
					props.detail.config!.calc.decimal = Number(props.detail.config!.calc.decimal);
					props.detail.config!.param.count = Number(props.detail.config!.param.count);
					props.detail.config!.param.offset = Number(props.detail.config!.param.offset);
					props.detail.config!.param.reg = Number(props.detail.config!.param.reg);
					emit("submit");
				}
			});
		};
		// 根据sn查询设备信息
		const getDeviceInfo = (idSn: string) => {
			getDevice({ idSn: idSn }).then((res: any) => {
				if (res.code == 200 && res.result) {
					if (res.result.protocol == "modbus") {
						state.isModbus = true;
					} else {
						state.isModbus = false;
					}
				}
			});
		};
		watchEffect(() => {
			if (attrs.visible) {
				if (!props.detail.param) {
					props.detail.param = { tags: [] };
				}
				if (!props.detail.config) {
					props.detail.config = { calc: {}, param: {}, upload: { mode: null, period: null } };
				}
				if (!props.detail.config.calc) {
					props.detail.config.calc = {};
				}
				if (!props.detail.config.param) {
					props.detail.config.param = {};
				}
				if (!props.detail.type) {
					props.detail.type = "string";
				}
				if (!props.detail.config!.type) {
					props.detail.config!.type = "float";
				}
				if (props.detail.sn) {
					getDeviceInfo(props.detail.sn);
				}
			}
		});
		return () => {
			return (
				<DialogBox {...attrs} width={props.width} title={props.title} onConfirm={validData} class="dialog-dense">
					<div class="variable-form">
						{attrs.visible ? (
							<el-form model={props.detail} ref={formRef} rules={formRule} label-width="100px" inline>
								<el-tabs model-value={state.view}>
									<el-tab-pane label={proxy?.$t("variable_basicdialog.tabpane.basics")} name="basics">
										<Basics detail={props.detail} devicePage={props.devicePage} isModbus={state.isModbus} />
									</el-tab-pane>
									{props.detail.sn && state.isModbus ? (
										<el-tab-pane label={proxy?.$t("variable_basicdialog.tabpane.advanced")} name="advanced">
											<ReadParam detail={props.detail} />
											<Calc detail={props.detail} />
										</el-tab-pane>
									) : null}
								</el-tabs>
							</el-form>
						) : null}
					</div>
				</DialogBox>
			);
		};
	}
});

const Calc = defineComponent({
	props: {
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {}, upload: {} }, param: {} };
			}
		}
	},
	setup(props) {
		if (props.detail.config?.calc.base == null) {
			props.detail.config!.calc.base = 0;
		}
		if (props.detail.config?.calc.mult == null) {
			props.detail.config!.calc.mult = 1;
		}
		if (props.detail.config?.calc.decimal == null) {
			props.detail.config!.calc.decimal = 0;
		}
		if (props.detail.config?.upload == null) {
			props.detail.config!.upload = {};
		}
		return () => {
			return (
				<>
					{/* <div class="group-title mt-8">数据处理</div> */}
					<el-form-item label="读功能码" prop="read">
						<el-select v-model={props.detail.config!.param.read} class="ant-col-type-select">
							{funcType.map((e: any) => {
								return h(
									<el-option
										value={e.value}
										label={e.label}
										disabled={props.detail.config?.param.access == 0 && (e.value == 2 || e.value == 4)}
									/>
								);
							})}
						</el-select>
					</el-form-item>
					<el-form-item label="写功能码" prop="write">
						<el-select
							v-model={props.detail.config!.param.write}
							class="ant-col-type-select"
							disabled={props.detail.config?.param.access == 1}
						>
							{control.map((e: any) => {
								return h(<el-option value={e.value} label={e.label} />);
							})}
						</el-select>
					</el-form-item>
					<el-form-item label="基础值" prop="base">
						<el-input v-model={props.detail.config!.calc.base} placeholder="基础值" style="width:214px" type="number" />
					</el-form-item>
					<el-form-item label="倍率" prop="mult">
						<div>
							<el-input v-model={props.detail.config!.calc.mult} placeholder="数据倍率" style="width:214px" type="number" />
							<div class="font-12 text-gray-400 leading-4">计算公式：变量 * 倍率 + 基础值</div>
						</div>
					</el-form-item>
					<el-form-item label="小数位" prop="decimal">
						<el-input v-model={props.detail.config!.calc.decimal} placeholder="数据小数位" style="width:214px" type="number" />
					</el-form-item>

					{/* <el-form-item label="上报模式" prop="mode">
						<el-select v-model={props.detail.config!.upload.mode} class="ant-col-type-select">
							{uploadMode.map((e: any) => {
								return h(<el-option value={e.value} label={e.label} />);
							})}
						</el-select>
					</el-form-item>
					<el-form-item label="上报周期(s)" prop="period">
						<el-input v-model={props.detail.config!.upload.period} placeholder="上报周期(s)" style="width:214px" type="number" />
					</el-form-item> */}
				</>
			);
		};
	}
});
const ReadParam = defineComponent({
	props: {
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {} }, param: {} };
			}
		}
	},
	setup(props) {
		if (props.detail.config?.param.reg == null) {
			props.detail.config!.param.reg = 0;
		}
		if (props.detail.config?.param.count == null) {
			props.detail.config!.param.count = 0;
		}
		if (props.detail.config?.param.offset == null) {
			props.detail.config!.param.offset = 0;
		}
		if (props.detail.config?.param.access == null) {
			props.detail.config!.param.access = 0;
		}
		return () => {
			return (
				<>
					{/* <div class="group-title">数据读取</div> */}
					<el-form-item label="寄存器地址" prop="reg">
						<el-input v-model={props.detail.config!.param.reg} placeholder="寄存器地址" style="width:214px" type="number" />
					</el-form-item>
					<el-form-item label="读写权限" prop="access">
						<el-select
							v-model={props.detail.config!.param.access}
							class="ant-col-type-select"
							onChange={() => {
								props.detail.config!.param.read = null;
								props.detail.config!.param.write = null;
							}}
						>
							{accessType.map((e: any) => {
								return h(<el-option value={e.value} label={e.label} />);
							})}
						</el-select>
					</el-form-item>
					{/* <el-form-item label="功能码" prop="read">
						<el-input v-model={props.detail.config!.param.read} placeholder="读取功能码" style="width:214px" />
					</el-form-item> */}
					<el-form-item label="读取个数" prop="count">
						<el-input v-model={props.detail.config!.param.count} placeholder="读取个数" style="width:214px" type="number" />
					</el-form-item>
					<el-form-item label="内部偏移" prop="offset">
						<el-input
							v-model={props.detail.config!.param.offset}
							placeholder="读取的内部偏移位"
							style="width:214px"
							type="number"
						/>
					</el-form-item>
				</>
			);
		};
	}
});
const Basics = defineComponent({
	props: {
		isModbus: { type: Boolean },
		devicePage: Boolean,
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {} }, param: {} };
			}
		}
	},
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const state = reactive({
			more: true,
			typeList: []
		});
		onMounted(() => {
			getTableList();
			if (props.isModbus) {
				props.detail.type = "number";
			}
		});
		const getTableList = async () => {
			let { result, code } = await getDictTypeList({ bizId: bizDictType.variable, pageIndex: 1, pageSize: 9999 });
			if (code == 200) {
				state.typeList = result.records;
			}
		};
		const dictTypeDialog = reactive({ visible: false, dictName: "", dictType: "" });
		const saveTypeDict = async () => {
			if (!dictTypeDialog.dictName || !dictTypeDialog.dictType) {
				showMsg("未填写参数", MessageType.error);
				return;
			}
			let { code, message } = await addDictType({
				status: 1,
				dictName: dictTypeDialog.dictName,
				dictType: dictTypeDialog.dictType,
				bizId: bizDictType.variable
			});
			let ok = showTips(code, "字典类型配置", message);
			if (ok) {
				await getTableList();
				dictTypeDialog.visible = false;
				props.detail.param!.dict = dictTypeDialog.dictType;
			}
		};
		return () => {
			return (
				<>
					<DialogBox
						v-model:visible={dictTypeDialog.visible}
						width="400"
						title={proxy?.$t("variable_basicdialog.dialog_title.addtype")}
						onConfirm={saveTypeDict}
					>
						<el-form-item label={proxy?.$t("variable_basicdialog.input_label.dictName")}>
							<el-input v-model={dictTypeDialog.dictName} placeholder={proxy?.$t("variable_basicdialog.placeholder.dictName")} />
						</el-form-item>
						<el-form-item label={proxy?.$t("variable_basicdialog.input_label.dictType")}>
							<el-input v-model={dictTypeDialog.dictType} placeholder={proxy?.$t("variable_basicdialog.placeholder.dictType")} />
						</el-form-item>
					</DialogBox>
					{!route.query.id ? (
						<el-form-item label={proxy?.$t("variable_basicdialog.form_label.sn")} prop="sn">
							<SelectDeviceList v-model={props.detail.sn} disabled={props.devicePage} />
						</el-form-item>
					) : null}
					<el-form-item
						label={proxy?.$t("variable_basicdialog.form_label.type")}
						prop="type"
						v-slots={{
							label: () => {
								return (
									<>
										<el-tooltip
											raw-content={true}
											show-after={500}
											width="400px"
											v-slots={{
												default: () => {
													return <i class="iconfont iconalert-circle" />;
												},
												content: () => {
													return (
														<div>
															<div>{proxy?.$t("variable_basicdialog.tooltip.type1")}</div>
															<div>{proxy?.$t("variable_basicdialog.tooltip.type2")}</div>
														</div>
													);
												}
											}}
										></el-tooltip>
										<span class="pl-1">{proxy?.$t("variable_basicdialog.form_label.type")}</span>
									</>
								);
							}
						}}
					>
						<el-select
							v-model={props.detail.type}
							class="ant-col-type-select"
							clearable
							filterable
							allow-create
							disabled={props.isModbus}
						>
							{Object.entries(TYPE_NAME).map((entrie: string[]) => {
								return <el-option value={entrie[0]} label={entrie[1]} />;
							})}
						</el-select>
					</el-form-item>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.label")} prop="label">
						<div style="width:214px">
							<el-input v-model={props.detail.label} placeholder={proxy?.$t("variable_basicdialog.placeholder.label")} />
						</div>
					</el-form-item>
					<el-form-item
						label={proxy?.$t("variable_basicdialog.form_label.key")}
						prop="key"
						v-slots={{
							label: () => {
								return (
									<>
										<el-tooltip
											raw-content={true}
											show-after={500}
											width="400px"
											v-slots={{
												default: () => {
													return <i class="iconfont iconalert-circle" />;
												},
												content: () => {
													return (
														<div>
															<div>{proxy?.$t("variable_basicdialog.tooltip.key1")}</div>
															<div>
																{proxy?.$t("variable_basicdialog.tooltip.key2")}
																<span class="text-red-600 p-1">.</span>
																{proxy?.$t("variable_basicdialog.tooltip.key3")}
															</div>
														</div>
													);
												}
											}}
										></el-tooltip>
										<span class="pl-1">{proxy?.$t("variable_basicdialog.form_label.key")}</span>
									</>
								);
							}
						}}
					>
						<div style="width:214px">
							<el-input
								v-model={props.detail.key}
								disabled={!!props.detail.id && !props.detail.copy}
								class="w-full"
								placeholder={proxy?.$t("variable_basicdialog.placeholder.key")}
							/>
						</div>
					</el-form-item>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.mode")} prop="mode">
						<el-select v-model={props.detail.config.upload.mode}>
							<el-option label="周期上报" value={2} />
							<el-option label="变化上报" value={1} />
						</el-select>
					</el-form-item>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.period")} prop="period">
						<div style="width:214px">
							<el-input
								v-model={props.detail.config.upload.period}
								placeholder={proxy?.$t("variable_basicdialog.placeholder.period")}
							/>
						</div>
					</el-form-item>
					{/* <div>
						<el-link class="ml-8 mb-2" type="primary" onClick={() => (state.more = !state.more)}>
							{state.more ? "更少" : "更多"}
							<i class={`iconfont ${state.more ? "iconchevrons-up" : "iconchevrons-down"}`}></i>
						</el-link>
					</div> */}
					{state.more ? <Advanced detail={props.detail} /> : null}
					{!props.isModbus ? (
						<el-form-item label={proxy?.$t("variable_basicdialog.form_label.access")} prop="access">
							<el-select
								v-model={props.detail.config!.param.access}
								class="ant-col-type-select"
								onChange={() => {
									props.detail.config!.param.read = null;
									props.detail.config!.param.write = null;
								}}
							>
								{accessType.map((e: any) => {
									return h(<el-option value={e.value} label={e.label} />);
								})}
							</el-select>
						</el-form-item>
					) : (
						""
					)}
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.dict")} prop="dict">
						<div class="flex" style="width:214px">
							<el-select v-model={props.detail.param!.dict} filterable class="flex-1" clearable>
								{state.typeList.map((item: any) => {
									return <el-option value={item.dictType} label={item.dictName}></el-option>;
								})}
							</el-select>
							<div
								class="w-16 text-center cursor-cell hover:text-blue-800"
								onClick={() => {
									dictTypeDialog.visible = true;
								}}
							>
								{proxy?.$t("variable_basicdialog.click.add")}
							</div>
						</div>
					</el-form-item>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.tags")} prop="tags">
						<Tags detail={props.detail} />
					</el-form-item>
				</>
			);
		};
	}
});

const Advanced = defineComponent({
	props: {
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {} }, param: {} };
			}
		}
	},
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		return () => {
			return (
				<>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.var_type")} prop="type">
						<el-select v-model={props.detail.config!.type} class="ant-col-type-select" clearable filterable allow-create>
							{TYPE_LIST.map((item: Select) => {
								return <el-option value={item.value} label={item.label} />;
							})}
						</el-select>
					</el-form-item>
					<el-form-item label={proxy?.$t("variable_basicdialog.form_label.unit")} prop="unit">
						<el-select v-model={props.detail.config!.unit} class="ant-col-type-select" clearable filterable allow-create>
							{UNIT_LIST.map((item: Select) => {
								return (
									<el-option value={item.value} label={item.label}>
										<div class="flex justify-between">
											<div>{item.label}</div>
											<div class="text-gray-400">{item.value}</div>
										</div>
									</el-option>
								);
							})}
						</el-select>
					</el-form-item>
				</>
			);
		};
	}
});

const Tags = defineComponent({
	props: {
		detail: {
			type: Object as PropType<Variable.ResVariable>,
			default() {
				return { config: { calc: {}, param: {} }, param: {} };
			}
		}
	},
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const inputEl = ref<any>();
		const state = reactive({
			inputVal: "",
			showInput: false
		});
		if (!props.detail.param?.tags) {
			props.detail.param!.tags = [];
		}
		const addTag = (e: any) => {
			if (e.keyCode == 13) {
				if (!props.detail.param?.tags.includes(state.inputVal)) {
					props.detail.param?.tags.push(state.inputVal);
					state.inputVal = "";
					state.showInput = false;
				}
			}
		};
		return () => {
			return (
				<div class="flex">
					{props.detail.param?.tags.map((v: string, i: number) => {
						return (
							<el-tag class="mr-1" closable disable-transitions={false} onClose={() => props.detail.param?.tags.splice(i, 1)}>
								{v}
							</el-tag>
						);
					})}

					{state.showInput ? (
						<el-tooltip show-after={500} content={proxy?.$t("variable_basicdialog.tip.content")}>
							<el-input
								ref={inputEl}
								v-model={state.inputVal}
								class="mr-1 w-20"
								size="small"
								onKeyup={addTag}
								onBlur={() => (state.showInput = false)}
								placeholder={proxy?.$t("variable_basicdialog.tip.placeholder")}
							/>
						</el-tooltip>
					) : (
						<el-button
							class="iconfont iconplus1 ml-1"
							size="small"
							onClick={() => {
								state.showInput = true;
								nextTick(() => {
									inputEl.value.focus();
								});
							}}
						>
							{proxy?.$t("variable_basicdialog.btn.add_tags")}
						</el-button>
					)}
				</div>
			);
		};
	}
});
